import json
from traceback import format_exc
from django.http import HttpResponse, JsonResponse
from sso_center.models import AppUser
from sso_center.my_encrypt import user_password_encrypt
from sso_center.token_method import create_token, check_user_token


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")


def login(request):
    try:
        json_str = request.body
        json_str = json_str.decode()
        json_data = json.loads(json_str)
        print(json_data)
        username = json_data["username"]
        # 对接收到的密码进行加密
        password = user_password_encrypt(username, json_data["password"])
        # 验证密码
        que_user = AppUser.objects.filter(username=username)
        # 用户存在
        if que_user:
            # 用户状态是否正常
            if que_user[0].status != '1':
                rsp = {
                    'code': 401,
                    'message': '用户状态非活动！'
                }
                response = JsonResponse(rsp, safe=False)
                return response
            # 密码不正确
            if que_user[0].password != password:
                # 密码错误10次后冻结账户
                if int(que_user[0].error_num) < 10:
                    que_user.update(error_num=str(int(que_user[0].error_num) + 1))
                else:
                    que_user.update(status='2')
                rsp = {
                    'code': 401,
                    'message': '用户名或密码错误！'
                }
                response = JsonResponse(rsp, safe=False)
                return response
            # 密码正确
            else:
                # 验证成功后，密码错误次数不为0时，刷新为0
                if que_user[0].error_num != '0':
                    que_user.update(error_num='0')
                # 生成令牌
                token = create_token(username)
                rsp = {
                    'token': token,
                    'code': 200,
                }
                response = JsonResponse(rsp, safe=False)
                response.status_code = 200
                return response
        # 用户不存在
        else:
            rsp = {
                'code': 401,
                'message': '用户名或密码错误！'
            }
            response = JsonResponse(rsp, safe=False)
            return response
    except Exception as e:
        print(str(format_exc()))
        response = JsonResponse(str(e), safe=False)
        response.status_code = 200
        return response


def verify(request):
    try:
        # 认证
        json_str = request.body.decode()
        json_data = json.loads(json_str)
        print(json_data)
        token = json_data["token"]
        username = json_data["username"]
        if not check_user_token(token, username):
            rsp = {
                'token': token,
                'code': 200,
            }
            response = JsonResponse(rsp, safe=False)
            response.status_code = 200
            return response
        rsp = {
            'code': 401,
            'message': '认证失败！'
        }
        response = JsonResponse(rsp, safe=False)
        return response
    except Exception as e:
        print(str(format_exc()))
        response = JsonResponse(str(e), safe=False)
        response.status_code = 200
        return response
